package com.jt.www.admin.market.service.impl;

import com.google.common.collect.Lists;
import com.jt.www.admin.market.service.TeamService;
import com.jt.www.dao.mapper.market.MarketerInfoMapper;
import com.jt.www.dao.mapper.market.TeamFounderMapper;
import com.jt.www.dao.mapper.market.TeamMapper;
import com.jt.www.dao.mapper.market.TeamMembersMapper;
import com.jt.www.domain.enums.common.YesOrNoEnum;
import com.jt.www.domain.enums.pc.TeamMembersLevelEnum;
import com.jt.www.domain.po.MarketerInfoEntity;
import com.jt.www.domain.po.TeamEntity;
import com.jt.www.domain.po.TeamFounderEntity;
import com.jt.www.domain.po.TeamMembersEntity;
import com.jt.www.domain.qo.SaveTeamMembersQO;
import com.jt.www.domain.qo.TeamFounderExportQO;
import com.jt.www.domain.qo.TeamFounderInfoQO;
import com.jt.www.domain.qo.TeamMembersQO;
import com.jt.www.domain.vo.*;
import com.jt.www.model.registerCustomer.vo.JtBranchInfoVo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.remote.UserClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeamServiceImpl implements TeamService {

    public static final Logger log = LoggerFactory.getLogger(TeamServiceImpl.class);
    private final static String SYS_CODE = "sys_edu_man";
    @Autowired
    TeamFounderMapper teamFounderMapper;
    @Autowired
    TeamMapper teamMapper;
    @Autowired
    TeamMembersMapper teamMembersMapper;
    @Autowired
    MarketerInfoMapper marketerInfoMapper;
    @Autowired
    UserClient userClient;

    @Override
    @Transactional
    public ResponseEntity saveTeamFounder(String findCode, TeamFounderEntity teamFounderEntity) {

        if (StringUtils.isBlank(teamFounderEntity.getMarketerNo())) {
            return GenericDataResponse.ng("工号不能为空");
        }

        //为空表示新建 否则更新
        if (teamFounderEntity.getId() == null) {
            //保存创始人信息
            teamFounderEntity.setCreateTime(DateUtils.getCurrentTime());
            teamFounderEntity.setIsDeleted(false);
            teamFounderMapper.insertSelective(teamFounderEntity);

            log.info("{} 团队创始人配置 保存创始人信息成功 teamFounderEntity->{}", findCode, JsonUtil.object2Json(teamFounderEntity));

            //更新营销人员表是否加入团队标识 isJoinTeam = true
            setIsJoinTeamFlag(findCode, teamFounderEntity.getMarketerNo(), true);

            //查询该营销人员基础信息
            List<MarketerInfoEntity> marketers = getMarketerByNo(teamFounderEntity.getMarketerNo());
            MarketerInfoEntity marketerInfoEntity = new MarketerInfoEntity();
            if (marketers != null && marketers.size() > 0) {
                marketerInfoEntity = marketers.get(0);
            }

            FounderInfoVO vo = FounderInfoVO.convertEntity(teamFounderEntity, marketerInfoEntity);
            //创建团队时将创始人添加到 小队成员信息表中
            teamMembersMapper.insertSelective(createTeamMembersEntity(teamFounderEntity));

            log.info("{} 团队创始人配置 组装返回结果 vo->{}", findCode, JsonUtil.object2Json(vo));

            return GenericDataResponse.okWithData(vo);

        } else {
            //查询原创始人表信息
            TeamFounderEntity team = teamFounderMapper.selectByPrimaryKey(teamFounderEntity.getId());
            if (team != null && !team.getIsDeleted()) {
                //更新创始人表信息
                team.setMarketerNo(teamFounderEntity.getMarketerNo());
                team.setTeamFounderName(teamFounderEntity.getTeamFounderName());
                team.setUpdateTime(DateUtils.getCurrentTime());
                teamFounderMapper.updateByPrimaryKeySelective(team);

                //更新营销人员是否入队标识 原创始人更新为false
                setIsJoinTeamFlag(findCode, team.getMarketerNo(), false);

                //更新营销人员是否入队标识 新创始人更新为true
                setIsJoinTeamFlag(findCode, teamFounderEntity.getMarketerNo(), true);

                //修改团队时将原创始人在小队成员信息表中删除
                TeamMembersEntity oldFounderTeamMember = new TeamMembersEntity();
                oldFounderTeamMember.setIsDeleted(true);
                Weekend<TeamMembersEntity> weekend = Weekend.of(TeamMembersEntity.class);
                WeekendCriteria<TeamMembersEntity, Object> criteria = weekend.weekendCriteria();
                criteria.andEqualTo(TeamMembersEntity::getTeamFounderId, teamFounderEntity.getId());
                criteria.andEqualTo(TeamMembersEntity::getLevelCode, TeamMembersLevelEnum.LEVEL_2.getCode());
                criteria.andEqualTo(TeamMembersEntity::getIsDeleted, false);

                teamMembersMapper.updateByExampleSelective(oldFounderTeamMember, weekend);
                //修改团队时将创始人添加到 小队成员信息表中
                teamMembersMapper.insertSelective(createTeamMembersEntity(teamFounderEntity));
                return GenericDataResponse.ok();
            } else {
                return GenericDataResponse.ng("根据创始人ID未查询到记录 ID->" + teamFounderEntity.getId());
            }
        }

    }

    private TeamMembersEntity createTeamMembersEntity(TeamFounderEntity teamFounderEntity) {
        TeamMembersEntity teamMembersEntity = new TeamMembersEntity();
        teamMembersEntity.setUserCode(teamFounderEntity.getUserCode());
        teamMembersEntity.setMarketerNo(teamFounderEntity.getMarketerNo());
        teamMembersEntity.setTeamFounderId(teamFounderEntity.getId());
        teamMembersEntity.setTeamId(0L);
        teamMembersEntity.setLevelCode(TeamMembersLevelEnum.LEVEL_2.getCode());
        teamMembersEntity.setLevelName(TeamMembersLevelEnum.LEVEL_2.getMsg());
        teamMembersEntity.setJoinTime(teamFounderEntity.getCreateTime());
        teamMembersEntity.setCreateTime(teamFounderEntity.getCreateTime());
        teamMembersEntity.setUpdateTime(teamFounderEntity.getCreateTime());
        teamMembersEntity.setIsDeleted(false);
        return teamMembersEntity;
    }


    @Override
    public ResponseEntity saveTeamMembers(String findCode, SaveTeamMembersQO saveTeamMembersQO) {

        if (saveTeamMembersQO.getTeamFounderId() == null) {
            return GenericDataResponse.ng("创始人ID不能为空");
        }

        if (saveTeamMembersQO.getMembers() == null || saveTeamMembersQO.getMembers().size() == 0) {
            return GenericDataResponse.ng("团队成员不能为空");
        }

        List<TeamMembersVO> list = new ArrayList<>();

        saveTeamMembersQO.getMembers().forEach(m -> {

            m.setTeamFounderId(saveTeamMembersQO.getTeamFounderId());
            m.setTeamId(m.getTeamId() != null ? m.getTeamId() : 0L);
            m.setLevelCode(StringUtils.isNotBlank(m.getLevelCode()) ? m.getLevelCode() : TeamMembersLevelEnum.LEVEL_1.getCode());
            m.setLevelName(StringUtils.isNotBlank(m.getLevelCode()) ? TeamMembersLevelEnum.getMsgByCode(m.getLevelCode()) : TeamMembersLevelEnum.LEVEL_1.getMsg());
            m.setCreateTime(DateUtils.getCurrentTime());
            m.setIsDeleted(false);

            teamMembersMapper.insertSelective(m);

            log.info("{} 团队成员配置 t_team_members表保存成功 m->{}", findCode, JsonUtil.object2Json(m));

            //更新营销人员表是否加入团队标识 isJoinTeam = true
            setIsJoinTeamFlag(findCode, m.getMarketerNo(), true);

            //组装返回信息
            TeamEntity team = null;
            if (m.getTeamId() != null && m.getTeamId() != 0) {
                TeamEntity example = new TeamEntity();
                example.setId(m.getTeamId());

                team = teamMapper.selectByPrimaryKey(example);
            }

            List<MarketerInfoEntity> marketers = getMarketerByNo(m.getMarketerNo());
            MarketerInfoEntity marketerInfoEntity = new MarketerInfoEntity();
            if (marketers != null && marketers.size() > 0) {
                marketerInfoEntity = marketers.get(0);
            }

            TeamMembersVO vo = TeamMembersVO.convertEntity(team, m, marketerInfoEntity);

            list.add(vo);
        });

        return GenericDataResponse.okWithData(list);
    }

    @Override
    public ResponseEntity<GenericListResponse<TeamEntity>> queryTeams(String findCode, String teamFounderId) {

        Weekend<TeamEntity> weekend = Weekend.of(TeamEntity.class);
        WeekendCriteria<TeamEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(TeamEntity::getTeamFounderId, teamFounderId);
        criteria.andEqualTo(TeamEntity::getIsDeleted, false);

        List<TeamEntity> list = teamMapper.selectByExample(weekend);

        TeamEntity team = new TeamEntity();
        team.setTeamName("创始人直属");
        team.setId(0L);

        list.add(team);
        list.stream().sorted(Comparator.comparing(TeamEntity::getId)).collect(Collectors.toList());//根据ID升序排

        return GenericListResponse.listAndCount(list, (long) list.size());
    }

    @Override
    public ResponseEntity<GenericListResponse<TeamMembersVO>> queryNoTeamMembersByFounderId(String findCode, Long teamFounderId, Long memberId) {

        List<TeamMembersVO> members = new ArrayList<>();

        Weekend<TeamMembersEntity> weekend = Weekend.of(TeamMembersEntity.class);
        WeekendCriteria<TeamMembersEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(TeamMembersEntity::getTeamFounderId, teamFounderId);
        criteria.andEqualTo(TeamMembersEntity::getIsDeleted, false);
        criteria.andEqualTo(TeamMembersEntity::getLevelCode, TeamMembersLevelEnum.LEVEL_1.getCode());
        criteria.andEqualTo(TeamMembersEntity::getTeamId, 0);

        weekend.setOrderByClause("id desc");

        List<TeamMembersEntity> list = teamMembersMapper.selectByExample(weekend);

        if (list != null && list.size() > 0) {

            if (null != memberId) {
                list.removeIf(m -> m.getId() == memberId);
            }

            if (list != null && list.size() > 0) {
                list.forEach(m -> {
                    Weekend<MarketerInfoEntity> marketerWeekend = Weekend.of(MarketerInfoEntity.class);
                    WeekendCriteria<MarketerInfoEntity, Object> marketerCriteria = marketerWeekend.weekendCriteria();
                    marketerCriteria.andEqualTo(MarketerInfoEntity::getMarketerNo, m.getMarketerNo());
                    marketerCriteria.andEqualTo(MarketerInfoEntity::getIsDeleted, false);

                    List<MarketerInfoEntity> marketers = marketerInfoMapper.selectByExample(marketerWeekend);

                    TeamMembersVO vo = new TeamMembersVO();

                    if (marketers != null && marketers.size() > 0) {
                        vo = TeamMembersVO.convertEntity(null, m, marketers.get(0));
                    }

                    members.add(vo);

                });
            }
        }

        return GenericListResponse.listAndCount(members, (long) members.size());
    }

    @Override
    public ResponseEntity updateTeamMember(String findCode, Long memberId, Long teamId, String levelCode,
                                           Long newTeamId, String memberIds) {
        //查询该成员修改配置之前是否是业务经理
        TeamMembersEntity old = teamMembersMapper.selectByPrimaryKey(memberId);
        log.info("{} 成员进/出队 根据memberId->{} 查询修改前信息 old->{}", findCode, memberId, JsonUtil.object2Json(old));

        // 业务经理 -> 业务员
        if (TeamMembersLevelEnum.LEVEL_0.getCode().equals(old.getLevelCode())
                && TeamMembersLevelEnum.LEVEL_1.getCode().equals(levelCode)) {
            log.info("{} 成员进/出队 业务经理->业务员", findCode);
            // 更新成员表信息
            TeamMembersEntity updMember = new TeamMembersEntity();
            updMember.setId(memberId);
            updMember.setTeamId(teamId);
            updMember.setLevelCode(levelCode);
            updMember.setLevelName(TeamMembersLevelEnum.getMsgByCode(levelCode));
            updMember.setJoinTime(DateUtils.getCurrentTime());
            updMember.setUpdateTime(DateUtils.getCurrentTime());
            teamMembersMapper.updateByPrimaryKeySelective(updMember);
            log.info("{} 成员进/出队 业务经理->业务员 更新成员信息表完成 member->{}", findCode, JsonUtil.object2Json(updMember));

            // 删除小队
            TeamEntity delTeam = new TeamEntity();
            delTeam.setId(old.getTeamId());
            delTeam.setIsDeleted(true);
            delTeam.setUpdateTime(DateUtils.getCurrentTime());
            teamMapper.updateByPrimaryKeySelective(delTeam);

            log.info("{} 成员进/出队 业务经理->业务员 删除小队(is_deleted=true) teamId->{}", findCode, old.getTeamId());


            // 原小队成员设置为新小队成员 （没有新小队时设置直属）
            Weekend<TeamMembersEntity> updWeekend = Weekend.of(TeamMembersEntity.class);
            WeekendCriteria<TeamMembersEntity, Object> updCriteria = updWeekend.weekendCriteria();
            updCriteria.andEqualTo(TeamMembersEntity::getTeamId, old.getTeamId());
            updCriteria.andEqualTo(TeamMembersEntity::getIsDeleted, false);

            TeamMembersEntity member = new TeamMembersEntity();
            member.setUpdateTime(DateUtils.getCurrentTime());
            member.setTeamId(null == newTeamId ? 0 : newTeamId);
            teamMembersMapper.updateByExampleSelective(member, updWeekend);
            log.info("{} 成员进/出队 业务经理->业务员 小队处置方式 1-转移至其他小队 目标小队ID->{}", findCode, newTeamId);
            return GenericDataResponse.ok();
        } else if (TeamMembersLevelEnum.LEVEL_1.getCode().equals(old.getLevelCode())
                && TeamMembersLevelEnum.LEVEL_0.getCode().equals(levelCode)) {
            // 业务员->业务经理

            log.info("{} 成员进/出队 业务员->业务经理", findCode);

            //新增小队
            Weekend<TeamEntity> queryWeekend = Weekend.of(TeamEntity.class);
            WeekendCriteria<TeamEntity, Object> queryCriteria = queryWeekend.weekendCriteria();
            queryCriteria.andEqualTo(TeamEntity::getTeamFounderId, old.getTeamFounderId());
            queryWeekend.setOrderByClause("id desc");
            List<TeamEntity> teams = teamMapper.selectByExample(queryWeekend);

            TeamEntity team = new TeamEntity();
            int maxNum;
            if (CollectionUtils.isNotEmpty(teams)) {
                maxNum = teams.get(0).getTeamNum() + 1;
            } else {
                maxNum = 1;
            }
            log.info("{} 成员进/出队 业务员->业务经理 新增小队 teamNum->{}", findCode, maxNum);
            team.setTeamName("业务小队-" + maxNum);
            team.setTeamNum(maxNum);
            team.setTeamFounderId(old.getTeamFounderId());
            team.setUserCode(old.getUserCode());
            team.setMarketerNo(old.getMarketerNo());
            team.setCreateTime(DateUtils.getCurrentTime());
            team.setIsDeleted(false);
            teamMapper.insertSelective(team);

            // 更新成员表信息
            TeamMembersEntity updMember = new TeamMembersEntity();
            updMember.setId(memberId);
            updMember.setTeamId(team.getId());
            updMember.setLevelCode(TeamMembersLevelEnum.LEVEL_0.getCode());
            updMember.setLevelName(TeamMembersLevelEnum.LEVEL_0.getMsg());
            updMember.setJoinTime(DateUtils.getCurrentTime());
            updMember.setUpdateTime(DateUtils.getCurrentTime());

            teamMembersMapper.updateByPrimaryKeySelective(updMember);

            log.info("{} 成员进/出队 业务员->业务经理 更新成员表信息 完成 member->{}", findCode, JsonUtil.object2Json(updMember));

            // 添加小队成员
            if (StringUtils.isNotBlank(memberIds)) {
                String[] memberIdArray = memberIds.split(",");
                for (int i = 0; i < memberIdArray.length; i++) {
                    TeamMembersEntity m = new TeamMembersEntity();
                    m.setId(Long.valueOf(memberIdArray[i]));
                    m.setTeamId(team.getId());
                    m.setUpdateTime(DateUtils.getCurrentTime());
                    m.setJoinTime(DateUtils.getCurrentTime());
                    m.setIsDeleted(false);
                    teamMembersMapper.updateByPrimaryKeySelective(m);
                }
            }

            return GenericDataResponse.ok();

        } else if (TeamMembersLevelEnum.LEVEL_1.getCode().equals(old.getLevelCode())
                && TeamMembersLevelEnum.LEVEL_1.getCode().equals(levelCode)) {// 业务员->业务员
            log.info("{} 成员进/出队 业务员更换小队", findCode);
            if (old.getTeamId() != teamId) {
                // 更新成员表信息
                TeamMembersEntity updMember = new TeamMembersEntity();
                updMember.setId(memberId);
                updMember.setTeamId(teamId);
                updMember.setJoinTime(DateUtils.getCurrentTime());
                updMember.setUpdateTime(DateUtils.getCurrentTime());
                teamMembersMapper.updateByPrimaryKeySelective(updMember);
                log.info("{} 成员进/出队 业务员更换小队 完成 member->{}", findCode, JsonUtil.object2Json(updMember));
            }
        } else {
            //业务经理->业务经理   即  添加小队成员
            log.info("{} 成员进/出队 添加小队成员", findCode);
            if (StringUtils.isNotBlank(memberIds)) {
                String[] memberIdArray = memberIds.split(",");
                for (int i = 0; i < memberIdArray.length; i++) {
                    TeamMembersEntity m = new TeamMembersEntity();
                    m.setId(Long.valueOf(memberIdArray[i]));
                    m.setTeamId(old.getTeamId());
                    m.setUpdateTime(DateUtils.getCurrentTime());
                    m.setJoinTime(DateUtils.getCurrentTime());
                    m.setIsDeleted(false);
                    teamMembersMapper.updateByPrimaryKeySelective(m);
                }
            }
        }
        return GenericDataResponse.ok();
    }

    @Override
    public ResponseEntity removeTeamMember(String findCode, String memberId) {

        // 查询成员信息
        TeamMembersEntity example = new TeamMembersEntity();
        example.setId(Long.valueOf(memberId));

        TeamMembersEntity old = teamMembersMapper.selectByPrimaryKey(example);

        log.info("{} 成员移除 根据memberId->{} 查询成员信息 old->{}", findCode, memberId, JsonUtil.object2Json(old));

        // 删除成员表信息
        TeamMembersEntity updMember = new TeamMembersEntity();
        updMember.setId(Long.valueOf(memberId));
        updMember.setIsDeleted(true);
        updMember.setUpdateTime(DateUtils.getCurrentTime());

        teamMembersMapper.updateByPrimaryKeySelective(updMember);

        log.info("{} 成员移除 更新成员信息(is_deleted=true) 完成", findCode);

        // 更新营销人员是否已经入队标识
        setIsJoinTeamFlag(findCode, old.getMarketerNo(), false);

        return GenericDataResponse.ok();
    }

    @Override
    public ResponseEntity resetTeamMembers(String findCode, String teamFounderId) {

        //删除创始人下所有小队
        Weekend<TeamEntity> teamWeekend = Weekend.of(TeamEntity.class);
        WeekendCriteria<TeamEntity, Object> teamCriteria = teamWeekend.weekendCriteria();
        teamCriteria.andEqualTo(TeamEntity::getTeamFounderId, teamFounderId);
        teamCriteria.andEqualTo(TeamEntity::getIsDeleted, false);

        TeamEntity team = new TeamEntity();
        team.setIsDeleted(true);
        team.setUpdateTime(DateUtils.getCurrentTime());

        teamMapper.updateByExampleSelective(team, teamWeekend);

        //查询创始人成员列表
        Weekend<TeamMembersEntity> memberWeekend = Weekend.of(TeamMembersEntity.class);
        WeekendCriteria<TeamMembersEntity, Object> memberCriteria = memberWeekend.weekendCriteria();
        memberCriteria.andEqualTo(TeamMembersEntity::getTeamFounderId, teamFounderId);
        memberCriteria.andEqualTo(TeamMembersEntity::getIsDeleted, false);
        List<TeamMembersEntity> members = teamMembersMapper.selectByExample(memberWeekend);

        if (members != null && members.size() > 0) {

            TeamMembersEntity updMember = new TeamMembersEntity();
            updMember.setIsDeleted(true);
            updMember.setUpdateTime(DateUtils.getCurrentTime());

            teamMembersMapper.updateByExampleSelective(updMember, memberWeekend);

            String marketerNos = members.stream().map(TeamMembersEntity::getMarketerNo).collect(Collectors.joining(","));
            setIsJoinTeamFlag(findCode, marketerNos, false);
//            members.forEach( m -> {
//                // 更新营销人员是否已经入队标识
//                setIsJoinTeamFlag(findCode, m.getMarketerNo(), false);
//            });
        }
        return GenericDataResponse.ok();

    }

    @Override
    public ResponseEntity<GenericDataResponse<TeamDetailVO>> queryDetailByTeamFounderId(String findCode, Long teamFounderId) {

        TeamDetailVO vo = new TeamDetailVO();

        List<TeamFounderInfoVO> founders = teamFounderMapper.queryTeamFounderDetail(teamFounderId);

        if (founders != null && founders.size() > 0) {
            vo.setFounder(founders.get(0));

            vo.setTeams(teamFounderMapper.queryTeamsDetail(teamFounderId));

            TeamMembersQO teamMembersQO = new TeamMembersQO();
            teamMembersQO.setTeamFounderId(teamFounderId);

            teamMembersQO.setLevelCode(TeamMembersLevelEnum.getNotFounder());
            vo.setMembers(teamFounderMapper.queryTeamMembersDetail(teamMembersQO));

        } else {
            return GenericDataResponse.errorWithMsg("未查询到该创始人信息 ID->" + teamFounderId, TeamDetailVO.class);
        }

        return GenericDataResponse.okWithData(vo);
    }

    @Override
    public ResponseEntity queryMembersByTeamId(String findCode, Long teamId) {

        TeamMembersQO teamMembersQO = new TeamMembersQO();
        teamMembersQO.setTeamId(teamId);
        teamMembersQO.setLevelCode(TeamMembersLevelEnum.LEVEL_1.getCode());

        List<TeamMembersVO> members = teamFounderMapper.queryTeamMembersDetail(teamMembersQO);

        return GenericListResponse.listAndCount(members, members.size());
    }

    @Override
    public ResponseEntity disbandTeamFounder(String findCode, Long teamFounderId) {


        // 查询创始人信息
        Weekend<TeamFounderEntity> teamFounderEntityWeekend = Weekend.of(TeamFounderEntity.class);
        WeekendCriteria<TeamFounderEntity, Object> teamFounderEntityCriteria = teamFounderEntityWeekend.weekendCriteria();
        teamFounderEntityCriteria.andEqualTo(TeamFounderEntity::getId, teamFounderId);
        teamFounderEntityCriteria.andEqualTo(TeamFounderEntity::getIsDeleted, false);

        TeamFounderEntity oldTeamFounder = teamFounderMapper.selectOneByExample(teamFounderEntityWeekend);

        log.info("{} 解散创始人团队 根据teamFounderId->{}查询到创始人信息 ->{}", findCode, teamFounderId, JsonUtil.object2Json(oldTeamFounder));

        // 删除创始人信息
        TeamFounderEntity teamFounderEntity = new TeamFounderEntity();
        teamFounderEntity.setUpdateTime(DateUtils.getCurrentTime());
        teamFounderEntity.setIsDeleted(true);

        teamFounderMapper.updateByExampleSelective(teamFounderEntity, teamFounderEntityWeekend);

        log.info("{} 解散创始人团队 删除创始人信息完成", findCode);

        // 更新营销人员是否加入团队标识
        setIsJoinTeamFlag(findCode, oldTeamFounder.getMarketerNo(), false);

        // 删除小队
        Weekend<TeamEntity> teamEntityWeekend = Weekend.of(TeamEntity.class);
        WeekendCriteria<TeamEntity, Object> teamEntityCriteria = teamEntityWeekend.weekendCriteria();
        teamEntityCriteria.andEqualTo(TeamEntity::getTeamFounderId, teamFounderId);
        teamEntityCriteria.andEqualTo(TeamEntity::getIsDeleted, false);

        TeamEntity teamEntity = new TeamEntity();
        teamEntity.setUpdateTime(DateUtils.getCurrentTime());
        teamEntity.setIsDeleted(true);

        teamMapper.updateByExampleSelective(teamEntity, teamEntityWeekend);

        log.info("{} 解散创始人团队 删除创始人小队信息完成", findCode);

        // 删除小队成员
        Weekend<TeamMembersEntity> teamMembersEntityWeekend = Weekend.of(TeamMembersEntity.class);
        WeekendCriteria<TeamMembersEntity, Object> teamMembersEntityCriteria = teamMembersEntityWeekend.weekendCriteria();
        teamMembersEntityCriteria.andEqualTo(TeamMembersEntity::getTeamFounderId, teamFounderId);
        teamMembersEntityCriteria.andEqualTo(TeamMembersEntity::getIsDeleted, false);

        List<TeamMembersEntity> members = teamMembersMapper.selectByExample(teamMembersEntityWeekend);

        TeamMembersEntity teamMembersEntity = new TeamMembersEntity();
        teamMembersEntity.setIsDeleted(true);
        teamMembersEntity.setUpdateTime(DateUtils.getCurrentTime());

        teamMembersMapper.updateByExampleSelective(teamMembersEntity, teamMembersEntityWeekend);

        log.info("{} 解散创始人团队 删除创始人小队成员信息完成", findCode);

        // 更新营销人员是否加入团队标识
        if (CollectionUtils.isNotEmpty(members)) {
            String marketerNos = members.stream().map(TeamMembersEntity::getMarketerNo).collect(Collectors.joining(","));
            setIsJoinTeamFlag(findCode, marketerNos, false);
        }
        return GenericDataResponse.ok();
    }

    @Override
    public ResponseEntity queryTeamFounders(String findCode, TeamFounderInfoQO teamFounderInfoQO) {

        if (StringUtils.isBlank(teamFounderInfoQO.getBranchCode())) {

            try {
                // 权限设置
                ResponseEntity<GenericDataResponse<Map<String, Object>>> responseEntity = userClient.queryUserRoleAndAuthority(teamFounderInfoQO.getUserCode(), SYS_CODE);
                LinkedHashMap<String, String> map = (LinkedHashMap) responseEntity.getBody().getData().get("dataPopedom");
                String jtBranchs = map.get("jtBranchs");
                log.debug("{} 分页查询创始人信息 用户中心返回值 jtBranchs = {}", findCode, jtBranchs);

                if (!"000000".equals(jtBranchs) && !"JT0000".equals(jtBranchs)) {//非全国

                    List<String> branchCodes = new ArrayList<>();
                    String[] branchs = jtBranchs.split(",");
                    for (String b : branchs) {
                        branchCodes.add(b);
                        GenericListResponse<JtBranchInfoVo> result = userClient.queryThirdGradeBranch(b);
                        if (result.getTotal() > 0) {
                            List<String> third = result.getList().stream()
                                    .map(JtBranchInfoVo::getCode)
                                    .collect(Collectors.toList());
                            branchCodes.addAll(third);
                        }
                    }
                    String branchCode = String.join(",", branchCodes);

                    teamFounderInfoQO.setBranchCode(branchCode);

                    log.info("{} 分页查询创始人信息 分支机构包含->{}", findCode, branchCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("{} 分页查询创始人信息 异常 e->{}", findCode, e);
                return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
            }
        }


        int total = teamFounderMapper.countTeamFounders(teamFounderInfoQO);
        if (total < 0) {
            return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
        }
        return GenericListResponse.listAndCount(teamFounderMapper.selectTeamFounders(teamFounderInfoQO), total);
    }

    @Override
    public List<TeamFounderInfoVO> exportTeamFounders(String findCode, TeamFounderExportQO teamFounderExportQO) {
        if (StringUtils.isBlank(teamFounderExportQO.getBranchCode())) {

            try {
                // 权限设置
                ResponseEntity<GenericDataResponse<Map<String, Object>>> responseEntity = userClient.queryUserRoleAndAuthority(teamFounderExportQO.getUserCode(), SYS_CODE);
                LinkedHashMap<String, String> map = (LinkedHashMap) responseEntity.getBody().getData().get("dataPopedom");
                String jtBranchs = map.get("jtBranchs");
                log.debug("{} 导出创始人信息 用户中心返回值 jtBranchs = {}", findCode, jtBranchs);

                if (!"000000".equals(jtBranchs) && !"JT0000".equals(jtBranchs)) {//非全国

                    List<String> branchCodes = new ArrayList<>();
                    String[] branchs = jtBranchs.split(",");
                    for (String b : branchs) {
                        branchCodes.add(b);
                        GenericListResponse<JtBranchInfoVo> result = userClient.queryThirdGradeBranch(b);
                        if (result.getTotal() > 0) {
                            List<String> third = result.getList().stream()
                                    .map(JtBranchInfoVo::getCode)
                                    .collect(Collectors.toList());
                            branchCodes.addAll(third);
                        }
                    }
                    String branchCode = String.join(",", branchCodes);

                    teamFounderExportQO.setBranchCode(branchCode);

                    log.info("{} 导出创始人信息 分支机构包含->{}", findCode, branchCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("{} 导出创始人信息 异常 e->{}", findCode, e);
                return null;
            }
        }

        return teamFounderMapper.exportTeamFounders(teamFounderExportQO);
    }


    /**
     * 更新营销人员表是否加入团队标识
     *
     * @param findCode
     * @param marketerNos
     * @param isJoinTeam
     */
    private void setIsJoinTeamFlag(String findCode, String marketerNos, Boolean isJoinTeam) {

        log.info("{} 更新营销人员表是否加入团队标识 入参 marketerNos->{}, isJoinTeam->{}", findCode, marketerNos, isJoinTeam);

        List<String> marketerNoList = Arrays.asList(marketerNos.split(","));

        Weekend<MarketerInfoEntity> weekend = Weekend.of(MarketerInfoEntity.class);
        WeekendCriteria<MarketerInfoEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andIn(MarketerInfoEntity::getMarketerNo, marketerNoList);
        criteria.andEqualTo(MarketerInfoEntity::getIsDeleted, false);

        MarketerInfoEntity marketerInfoEntity = new MarketerInfoEntity();
        marketerInfoEntity.setIsJoinTeam(isJoinTeam);

        marketerInfoMapper.updateByExampleSelective(marketerInfoEntity, weekend);

        log.info("{} 更新营销人员表是否加入团队标识 更新完成", findCode);
    }

    /**
     * 根据工号查询营销人员信息
     *
     * @param marketerNo
     * @return
     */
    private List<MarketerInfoEntity> getMarketerByNo(String marketerNo) {
        Weekend<MarketerInfoEntity> weekend = Weekend.of(MarketerInfoEntity.class);
        WeekendCriteria<MarketerInfoEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(MarketerInfoEntity::getMarketerNo, marketerNo);
        criteria.andEqualTo(MarketerInfoEntity::getIsDeleted, false);

        return marketerInfoMapper.selectByExample(weekend);
    }

    @Override
    public List<CommissionTeamVO> queryTeamByMarketerNo(String marketerNo, YesOrNoEnum allHistory) {
        return teamFounderMapper.queryTeamByMarketerNo(marketerNo, allHistory.getType());
    }

    @Override
    public List<FounderVo> queryTeamFoundersByBranchCode(String branchCode) {
        return teamFounderMapper.queryTeamFoundersByBranchCode(branchCode);
    }
}
